package cn.iocoder.yudao.module.shop.service.variable;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.shop.controller.admin.variable.vo.*;
import cn.iocoder.yudao.module.shop.dal.dataobject.variable.ShopVariableDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.shop.convert.variable.ShopVariableConvert;
import cn.iocoder.yudao.module.shop.dal.mysql.variable.ShopVariableMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.shop.enums.ErrorCodeConstants.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

/**
 * 零散变量 Service 实现类
 *
 * @author 曹建伟
 */
@Service
@Validated
public class ShopVariableServiceImpl implements ShopVariableService {

    @Resource
    private ShopVariableMapper variableMapper;

    @Override
    public Long createVariable(ShopVariableCreateReqVO createReqVO) {
        // 插入
        ShopVariableDO variable = ShopVariableConvert.INSTANCE.convert(createReqVO);
        variableMapper.insert(variable);
        // 返回
        return variable.getId();
    }

    @Override
    public void updateVariable(ShopVariableUpdateReqVO updateReqVO) {
        // 校验存在
        validateVariableExists(updateReqVO.getId());
        // 更新
        ShopVariableDO updateObj = ShopVariableConvert.INSTANCE.convert(updateReqVO);
        variableMapper.updateById(updateObj);
    }

    @Override
    public void deleteVariable(Long id) {
        // 校验存在
        validateVariableExists(id);
        // 删除
        variableMapper.deleteById(id);
    }

    private void validateVariableExists(Long id) {
        if (variableMapper.selectById(id) == null) {
            throw exception(VARIABLE_NOT_EXISTS);
        }
    }

    @Override
    public ShopVariableDO getVariable(Long id) {
        return variableMapper.selectById(id);
    }

    @Override
    public List<ShopVariableDO> getVariableList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return variableMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<ShopVariableDO> getVariablePage(ShopVariablePageReqVO pageReqVO) {
        return variableMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ShopVariableDO> getVariableList(ShopVariableExportReqVO exportReqVO) {
        return variableMapper.selectList(exportReqVO);
    }

}
